package utils

import (
	"bytes"
	"io/ioutil"
	"strings"
	"unicode"

	"golang.org/x/text/encoding/simplifiedchinese"
	"golang.org/x/text/transform"
)

// GbkToUtf8 gbk转utf8
func GbkToUtf8(s string) (string, error) {
	reader := transform.NewReader(bytes.NewReader([]byte(s)), simplifiedchinese.GBK.NewDecoder())

	d, e := ioutil.ReadAll(reader)

	if e != nil {
		return "", e
	}

	return string(d), nil
}

// Utf8ToGbk utf8转gbk
func Utf8ToGbk(s string) (string, error) {
	reader := transform.NewReader(bytes.NewReader([]byte(s)), simplifiedchinese.GBK.NewEncoder())

	d, e := ioutil.ReadAll(reader)

	if e != nil {
		return "", e
	}

	return string(d), nil
}

// CamelToSnake 驼峰命名转成蛇形命名，如果不是驼峰命名，则转成对应小写字符串，如： UserAgent → user_agent ，User → user
func CamelToSnake(camelCase string) string {
	var result strings.Builder
	for i, c := range camelCase {
		if unicode.IsUpper(c) && i > 0 {
			result.WriteByte('_')
		}
		result.WriteRune(unicode.ToLower(c))
	}
	return result.String()
}

// SnakeToCamel 蛇形转驼峰,如： device_id → DeviceId ，create_time → CreateTime ，location  → Location
func SnakeToCamel(snakeCase string) string {
	if snakeCase == "" {
		return ""
	}

	temp := strings.Split(snakeCase, "_")
	var s string
	for _, v := range temp {
		vv := []rune(v)
		if len(vv) > 0 {
			//首字母大写
			if vv[0] >= 'a' && vv[0] <= 'z' {
				vv[0] -= 32
			}
			s += string(vv)
		}
	}

	return s
}

// BigCamelToSmallCamel 大驼峰格式的字符串转小驼峰格式的字符串，如：UserAgent → userAgent
func BigCamelToSmallCamel(input string) string {
	if len(input) == 0 {
		return input
	}

	firstChar := strings.ToLower(string(input[0]))
	return firstChar + input[1:]
}

// CapitalizeFirstLetter 将首字母转换为大写，如： user → User
func CapitalizeFirstLetter(input string) string {
	if len(input) == 0 {
		return input
	}

	firstChar := []rune(input)[:1]
	firstCharUpper := string(unicode.ToUpper(firstChar[0]))

	return firstCharUpper + input[1:]
}
